package com.huijie.app.configuration;

import com.google.common.base.Predicate;
import org.jsets.shiro.config.ShiroProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;

/**
 * @ClassName Swagger2
 * @Description Swagger2 配置器
 * @Author Alex
 * @Date 2018/9/18 9:26
 * @Version 1.0
 */
@Configuration
public class Swagger2 {

    private final static String STR_PACKAGE =  "com.huijie.app";
 
	@Bean
	public Docket createRestApi() {
		
		//添加head参数start
    	ParameterBuilder tokenPar = new ParameterBuilder();
    	List<Parameter> pars = new ArrayList<>();
    	tokenPar.name(ShiroProperties.HEADER_JWT).description("JWT令牌").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
    	pars.add(tokenPar.build());
		
		return new Docket(DocumentationType.SWAGGER_2)
				.apiInfo(apiInfo())
				.select()
				.apis(Swagger2.basePackage())
//				.apis(RequestHandlerSelectors.basePackage("com.cn.rfid.controller.bus"))
				.paths(PathSelectors.any())
				.build().globalOperationParameters(pars);
	}
	
	private static Predicate<RequestHandler> basePackage() {
        return input -> {
            assert input != null;
            return declaringClass(input).map(handlerPackage()).orElse(true);
        };
    }
	
	private static Optional<Class<?>> declaringClass(RequestHandler input) {
        return Optional.ofNullable(input.declaringClass());
    }
	
	private static Function<Class<?>, Boolean> handlerPackage() {
        return input -> {
			for (String strPackage : STR_PACKAGE.split(",")) {
				boolean isMatch = input.getPackage().getName().startsWith(strPackage);
				if (isMatch) {
					return true;
				}
			}
			return false;
		};
	}

	private ApiInfo apiInfo() {
		return new ApiInfoBuilder()
				.title("系统平台Api文档")
				.description("简单优雅的restful风格~")
//				.termsOfServiceUrl("http://blog.csdn.net/saytime")
//				.contact(new Contact("name", "url", "email"))
				.version("1.0")
				.build();
	}
}
